package user.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import core.constants.Constant;
import core.enums.ExamListType;
import core.enums.ResultCode;
import core.exception.ServiceException;
import core.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import user.domain.exam.dto.ExamQueryDTO;
import user.domain.exam.dto.ExamRankDTO;
import user.domain.exam.vo.ExamRankVO;
import user.domain.exam.vo.ExamVO;
import user.domain.question.ExamQuestion;
import user.domain.user.UserExam;
import user.mapper.CExamMapper;
import user.domain.exam.Exam;
import user.mapper.CExamQuestionMapper;
import user.mapper.CUserExamMapper;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ExamCacheManage {
    @Autowired
    private RedisService redisService;

    @Autowired
    private CExamMapper examMapper;

    @Autowired
    private CUserExamMapper userExamMapper;

    @Autowired
    private CExamQuestionMapper examQuestionMapper;

    public Long getListSize(Integer examListType, Long userId) {  // type 0: 未完赛 1 : 已完赛
        String examListKey = getExamListKey(examListType, userId);
        return redisService.getListSize(examListKey);
    }

    public Long getExamQuestionListSize(Long examId){
        return redisService.getListSize(Constant.EXAM_QUESTION_LIST + examId);
    }
    private String getExamListKey(Integer examListType, Long userId) {
        if (ExamListType.EXAM_ING_LIST.getValue().equals(examListType)) {
            return Constant.ING_EXAM_LIST_KEY;
        } else if (ExamListType.EXAM_ED_LIST.getValue().equals(examListType)) {
            return Constant.ED_EXAM_LIST_KEY;
        } else {
            return Constant.USER_EXAM_LIST + userId;
        }
    }

    public void refreshCache(Integer type, Long userId) {
        List<Exam> examList;
        if(ExamListType.EXAM_ING_LIST.getValue().equals(type)) {
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .eq(Exam::getStatus, Constant.TRUE)
                    .gt(Exam::getEndTime, LocalDateTime.now()) // 未完成竞赛, 需大于当前时间
                    .orderByDesc(Exam::getCreateTime));
        } else if(ExamListType.EXAM_ED_LIST.getValue().equals(type)) {
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .eq(Exam::getStatus, Constant.TRUE)
                    .le(Exam::getEndTime, LocalDateTime.now()) // 已完成竞赛, 需小于等于当前时间
                    .orderByDesc(Exam::getCreateTime));
        } else {
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            examList = BeanUtil.copyToList(examVOList, Exam.class);
        }
        if(CollectionUtil.isEmpty(examList)){
            return;
        }
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);
        redisService.deleteObject(getExamListKey(type, userId));
        redisService.rightPushAll(getExamListKey(type, userId), examIdList);
    }

    private String getDetailKey(Long examId) {
        return Constant.EXAM_DETAIL_KEY + examId;
    }

    private String getUserExamListKey(Long userId) {
        return Constant.USER_EXAM_LIST + userId;
    }
    public List<ExamVO> getExamVOList(ExamQueryDTO query, Long userId) {
        int start = (query.getPageNum() - 1) * query.getPageSize();
        int end = start + query.getPageSize() - 1;
        String examListKey = getExamListKey(query.getType(), userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            // 说明 redis 中数据存在问题, 从数据库中查询, 并刷新缓存
            examVOList = userId == null ? getExamVOByDB(query) : getExamVOByDB(query, userId);
            refreshCache(query.getType(), userId);
        }
        return examVOList;
    }

    public void addUserExamList(Long userId, Long examId) {
        redisService.leftPushForList(getUserExamListKey(userId), examId);
    }

    private List<ExamVO> getExamVOByDB(ExamQueryDTO examListDTO) {
        PageHelper.startPage(examListDTO.getPageNum(), examListDTO.getPageSize());
        return examMapper.selectExamList(examListDTO);
    }

    private List<ExamVO> getExamVOByDB(ExamQueryDTO examListDTO, Long userId) {
        PageHelper.startPage(examListDTO.getPageNum(), examListDTO.getPageSize());
        return userExamMapper.selectUserExamList(userId);
    }
    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if(CollectionUtil.isEmpty(examIdList)){
            return null;
        }
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId)); // 拼接key
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        CollUtil.removeNull(examVOList);
        if(CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()){
            return null;
        }
        return examVOList;
    }

    public List<Long> getUserAllExamList(Long userId) {
        String userExamListKey = getUserExamListKey(userId);
        List<Long> userExamIdList = redisService.getCacheListByRange(userExamListKey, 0, -1, Long.class);
        if(CollectionUtil.isEmpty(userExamIdList)){
            List<UserExam> examVOList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                    .select(UserExam::getExamId)
                    .eq(UserExam::getUserId, userId));
            if(CollectionUtil.isEmpty(examVOList)){
                return null;
            }
            refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            userExamIdList = examVOList.stream().map(UserExam::getExamId).toList();
        }
        return userExamIdList;
    }

    public void refreshExamQuestionCache(Long examId) {
        List<ExamQuestion> examQuestions = examQuestionMapper
                .selectList(new LambdaQueryWrapper<ExamQuestion>()
                        .eq(ExamQuestion::getExamId, examId)
                        .orderByAsc(ExamQuestion::getQuestionOrder));
        if(CollectionUtil.isEmpty(examQuestions)){
            return;
        }
        List<Long> questionList = examQuestions.stream().map(ExamQuestion::getQuestionId).toList();
        redisService.rightPushAll(Constant.EXAM_QUESTION_LIST + examId, questionList);
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), LocalDateTime.now()
                .plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(Constant.EXAM_QUESTION_LIST + examId, seconds);
    }

    public String getFirstQuestion(Long examId) {
        return redisService.indexForList(Constant.EXAM_QUESTION_LIST + examId, 0, Long.class).toString();
    }

    public Long preQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(Constant.EXAM_QUESTION_LIST + examId, questionId);
        if (index <= 0) {
            throw new ServiceException(ResultCode.FIRST_QUESTION);
        }
        return redisService.indexForList(Constant.EXAM_QUESTION_LIST + examId, index - 1, Long.class);
    }

    public Long nextQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(Constant.EXAM_QUESTION_LIST + examId, questionId);
        if (index >= getExamQuestionListSize(examId) - 1) {
            throw new ServiceException(ResultCode.LAST_QUESTION);
        }
        return redisService.indexForList(Constant.EXAM_QUESTION_LIST + examId, index + 1, Long.class);
    }

    public Long getRankListSize(Long examId) {
        return redisService.getListSize(getExamRankListKey(examId));
    }

    private String getExamRankListKey(Long examId){
        return Constant.EXAM_RANK_LIST + examId;
    }

    public void refreshExamRankCache(Long examId) {
        List<ExamRankVO> examRankVOList = userExamMapper.selectExamRankList(examId);
        if(CollectionUtil.isEmpty(examRankVOList)){
            return;
        }
        redisService.rightPushAll(getExamRankListKey(examId), examRankVOList);
    }

    public List<ExamRankVO> getExamRankList(ExamRankDTO examRankDTO) {
        int start = (examRankDTO.getPageNum() - 1) * examRankDTO.getPageSize();
        int end = start + examRankDTO.getPageSize() - 1;
        return redisService.getCacheListByRange(getExamRankListKey(examRankDTO.getExamId()), start, end, ExamRankVO.class);
    }
}
